#include "temu.h"
#include "monitor.h"
#include "../lib/temuUI.h"

#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>

#define TRUE 1
#define FALSE 0
#define NR_CMD (sizeof(cmd_table) / sizeof(cmd_table[0]))

typedef struct
{
	char *name;
	char *description;
	int (*handler) (char *);
} Cmd_table;

extern Cmd_table cmd_table[];

void init_monitor();
void restart();
void ui_mainloop();
void cpu_exec(volatile uint32_t n);

void launch_temu(){
    init_monitor();
	restart();
	temu_state = STOP;
}

char* cmd_ui(char* str){
	char *str_end = str + strlen(str);
	if (str == NULL)
	{
		printf("cmd = NULL !!\n");
		return NULL;
	}
	char *cmd = strtok(str, " ");
	printf("accept cmd = %s \n", cmd);
	if (cmd == NULL)
		goto bad_cmd;
	char *args = cmd + strlen(cmd) + 1;
	if(args >= str_end) {
			args = NULL;
	}

	int i;
	for(i = 0; i < 7; i ++) {
		if(strcmp(cmd, cmd_table[i].name) == 0) {
			if(cmd_table[i].handler(args) < 0) {
				break;
			}
			break;
		}
	}

	if(i == 7) { printf("Unknown command '%s'\n", cmd); }
	return NULL;
bad_cmd:
	printf("recv bad command : %s \n", str);
	return NULL;
}

unsigned int get_pc(){
	return cpu.pc;
}

void step(){
	cpu_exec(1);
}

void temu_continue(){
	cpu_exec(-1);
}
